package com.gitee.funcy.multiple.datasource.interceptor;


import com.gitee.funcy.multiple.datasource.datasource.AppStorageContextHolder;
import com.gitee.funcy.multiple.datasource.domain.App;
import com.gitee.funcy.multiple.datasource.service.IAppService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * appDataSource 拦截器
 *
 * 获取请求中的dataSource，并保存到AppStorageContextHolder
 *
 * @author funcy
 * @date 2019-09-05
 *
 */
@Slf4j
@Component
public class AppDataSourceInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(AppDataSourceInterceptor.class);

	private final String PARAM_APP_ID = "appId";

	@Autowired
	private IAppService appService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String appId = request.getParameter(PARAM_APP_ID);
		if(StringUtils.isNotBlank(appId)) {
			App app = appService.selectById(NumberUtils.toLong(appId));
			if(null != app) {
				AppStorageContextHolder.setApp(app.getDataSource());
			}
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		AppStorageContextHolder.remove();
	}

}
